﻿using System;
using System.Web;
using System.Web.Caching;
using System.Collections;

namespace CSharp.Common.Cache
{
    public class CacheHelper
    {
  
        public static object GetCache(string cacheKey)
        {
            return HttpRuntime.Cache[cacheKey];
        }

        public static void SetCache(string cacheKey, object cacheTarget,CacheDependency dependency)
        {
            HttpRuntime.Cache.Insert(cacheKey, cacheTarget, dependency, DateTime.MaxValue, GetCurrentSessionOutTime(), CacheItemPriority.NotRemovable, null);
        }

        public static void SetCache(string CacheKey, object cacheTarget, CacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            HttpRuntime.Cache.Insert(CacheKey, cacheTarget, dependency, absoluteExpiration, slidingExpiration);
        }

        public static void RemoveAllCache(string CacheKey)
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            _cache.Remove(CacheKey);
        }

        public static void RemoveAllCache()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                _cache.Remove(CacheEnum.Key.ToString());
            }
        }

        private static TimeSpan GetCurrentSessionOutTime()
        {
            return new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
        }
    }
}

